package com.montran.generatedID;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;





@SuppressWarnings("unchecked")
public class GeneratedID {
	private volatile static GeneratedID instancia;
	private final String CONF_FILE = "conf/IdGenerator.data";
	private Map<String, String> dataMapId = new ConcurrentHashMap<String, String>();
	
	private GeneratedID(){
		try {
			FileInputStream fin = new FileInputStream(CONF_FILE);
			if (fin.available() != 0) {
				ObjectInputStream ois = new ObjectInputStream(fin);
				dataMapId = (ConcurrentHashMap<String, String>) ois.readObject();
				ois.close();
				fin.close();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static GeneratedID getInstance() {
		if (instancia == null) {
			synchronized (GeneratedID.class) {
				if (instancia == null) {
					instancia = new GeneratedID();
				}
				
			}
		}
		return instancia;
	}
	
	

	public synchronized String generatedId(Class<?> classType, Character prefix) {
		String key = classType.getName();
		Long longIdo = 1l;
		if(dataMapId.containsKey(key)){
			String oldId = dataMapId.get(key);
			longIdo = Long.valueOf(oldId.substring(1));
			longIdo++;
		}
		String id = prefix.toString()+longIdo;
		dataMapId.put(key, id);
	
		
		return id;
	}
	
	public synchronized void recordIdOnFile(){
		try {
			FileOutputStream fout = new FileOutputStream(CONF_FILE);
			ObjectOutputStream oos = new ObjectOutputStream(fout);
			oos.writeObject(dataMapId);
			oos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
